package com.qf.fmall2302.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmall2302.websocket.VoteWebSocketServer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.*;

@Component
public class MyTask {

    @Scheduled(cron = "*/5 * * * * *")
    public void test1() throws IOException {
        System.out.println("定时任务执行了........"+new Date());
        // 判断有没有需要推送数据的websocket连接存在，如果有就推，没有就什么都不做
        HashMap<String, Session> sessionHashMap = VoteWebSocketServer.sessionHashMap;
        if (sessionHashMap.size()>0){

            //1. 准备要推送的数据
            HashMap<String, Object> data1 = new HashMap<>();
            data1.put("name","luffy");
            data1.put("voteNum",new Random().nextInt(1000));

            HashMap<String, Object> data2 = new HashMap<>();
            data2.put("name","zoro");
            data2.put("voteNum",new Random().nextInt(1000));

            List<HashMap<String, Object>> list = Arrays.asList(data1, data2);
            // list ---> JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(list);

            //2. 遍历map中的所有连接，进行数据的推送
            for (Map.Entry<String, Session> sessionEntry : sessionHashMap.entrySet()) {
                Session session = sessionEntry.getValue();
                session.getBasicRemote().sendText(json);
            }


        }else {
            System.out.println("没有需要推送的连接，啥都不做");
        }
    }

}
